<template>
    <div class="comment-management-container">
        <div class="search-container">
            <el-input v-model="searchQuery" placeholder="请输入评论内容" class="search-input" clearable />
            <el-select v-model="statusFilter" placeholder="状态" class="status-select" clearable>
                <el-option label="已审核" :value="StatusType.Allow" />
                <el-option label="未审核" :value="StatusType.Prohibit" />
            </el-select>
            <el-button type="primary" @click="handleSearch">
                <el-icon>
                    <Search />
                </el-icon>
                搜索
            </el-button>
        </div>

        <div class="table-operations">
            <el-button type="danger" :disabled="selectedComments.length === 0" @click="handleBatchDelete">
                批量删除
            </el-button>
            <el-button type="success" :disabled="selectedComments.length === 0" @click="handleBatchApprove">
                批量审核
            </el-button>
        </div>

        <el-table :data="commentList" style="width: 85%;margin-left: 7%;" border v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isRowSelectable"/>
            <el-table-column label="菜谱图片" width="120">
                <template #default="scope">
                    <el-image :src="scope.row.recipeImg" :preview-src-list="[scope.row.recipeImg]" fit="cover"
                        style="width: 80px; height: 80px;" />
                </template>
            </el-table-column>
            <el-table-column prop="cookbName" label="关联菜谱名字" width="120" />
            <el-table-column prop="userName" label="评论人用户名" width="120" />
            <el-table-column prop="content" label="评论内容" width="250" />
            <el-table-column prop="createdTime" label="创建时间" width="180" />
            <el-table-column prop="reviewedTime" label="审核时间" width="180" />
            <el-table-column label="状态" width="150">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                        {{ scope.row.status === 1 ? '已审核' : '未审核' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <div class="operation-buttons">
                        <el-button size="small" type="success" v-if="scope.row.status === 0"
                            @click="approveComment(scope.row)">
                            通过
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { StatusType, type CommentTable } from "@/api/comment/commentModel";
import { useAdminStore } from "@/store/admin";
import { adminEditCommentListApi, adminGetCommentApi, deleteCommentApi } from "@/api/comment";

const useAdmin = useAdminStore()

// 定义表格行的类型接口
interface TableRow {
  name: string;
  status: string | number;  // 根据实际情况选择类型（字符串或数字）
  // 其他字段...
}

// 判断行是否可选（修改后的逻辑）
const isRowSelectable = (row: TableRow, index: number): boolean => {
  // 当 status 为 1 时返回 false（不可选）
  return row.status !== 1;  // 如果 status 是字符串类型，需改成 row.status !== '1'
};

// 数据加载状态
const loading = ref(false);
const commentList = ref<CommentTable[]>([]);
const searchQuery = ref("");
const statusFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedComments = ref<CommentTable[]>([]);

// 获取评论列表
const fetchComments = async () => {
    loading.value = true;
    try {
        const res = await adminGetCommentApi(currentPage.value, pageSize.value, searchQuery.value, statusFilter.value);
        if (res?.code === 200) {
            commentList.value = res.data.list;
            total.value = res.data.total;
        } else {
            ElMessage.error(res?.msg || '获取评论失败');
        }
    } catch (error) {
        console.error("获取评论失败:", error);
        ElMessage.error('获取评论失败');
    } finally {
        loading.value = false;
    }
};

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1;
    fetchComments();
};

// 分页处理
const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    fetchComments();
};

const handleCurrentChange = (page: number) => {
    currentPage.value = page;
    fetchComments();
};

// 表格选择
const handleSelectionChange = (selection: CommentTable[]) => {
    selectedComments.value = selection;
};

// 单个审核
const approveComment = async (comment: CommentTable) => {
    try {
        selectedComments.value.push(comment)
        if(useAdmin.admin){
            const res = await adminEditCommentListApi(selectedComments.value,useAdmin.admin.adminId);
            if (res.code === 200) {
            fetchComments();
            ElMessage.success(res.msg)
            ElMessage.success("审核了"+res.data+"条数据")
        }
        }
    } catch (error) {
        console.error("审核失败:", error);
        ElMessage.error('审核失败');
    }
};

// 批量审核
const handleBatchApprove = () => {
    if (selectedComments.value.length === 0) return;

    ElMessageBox.confirm('确定批量通过选中的评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if(useAdmin.admin){
            const res = await adminEditCommentListApi(selectedComments.value,useAdmin.admin.adminId);
            if (res.code === 200) {
            fetchComments();
            ElMessage.success(res.msg)
            ElMessage.success("审核了"+res.data+"条数据")
        }
        }
    }).catch(() => {});
};

// 删除操作
const handleDelete = (comment: CommentTable) => {
    ElMessageBox.confirm(`确定删除这条评论？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteCommentApi(comment.commentId);
            if (res?.code === 200) {
                ElMessage.success('删除成功');
                fetchComments();
            }
        } catch (error) {
            console.error("删除失败:", error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
    if (selectedComments.value.length === 0) return;

    ElMessageBox.confirm(`确定删除选中的 ${selectedComments.value.length} 条评论？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const promises = selectedComments.value.map(c => deleteCommentApi(c.commentId));
        
        try {
            await Promise.all(promises);
            ElMessage.success('批量删除成功');
            fetchComments();
        } catch (error) {
            console.error("批量删除失败:", error);
            ElMessage.error('部分删除失败');
        }
    }).catch(() => {});
};

onMounted(() => {
    fetchComments();
});
</script>

<style scoped>
.comment-management-container {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
}

.search-input {
    width: 300px;
}

.status-select {
    width: 120px;
}

.table-operations {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.operation-buttons {
    display: flex;
    gap: 5px;
}
</style>